﻿using System;
using DBProvider.Providers;

namespace HealthCommunity
{
	public partial class PasswordReset : System.Web.UI.Page
	{
		private IUserProvider _UserProvider;

		protected void Page_Load(object sender, EventArgs e)
		{
			if (!IsPostBack)
			{
				BindCurrentUser();
			}
		}

		protected void btnSave_Click(object sender, EventArgs e)
		{
			var user = SiteContext.Current.CurrentUser;

			if (user != null && user.UserID > 0)
			{
				user.SecretAnswer1 = txtSecretAnswer1.Text.Trim();
				user.SecretAnswer2 = txtSecretAnswer2.Text.Trim();
				user.SecretQuestion1 = txtSecretQuestion1.Text.Trim();
				user.SecretQuestion2 = txtSecretQuestion2.Text.Trim();
				user.UserPassword = txtNewPwd.Text;

				if (_UserProvider == null)
				{
					_UserProvider = new UserProvider();
				}

				var msg = string.Empty;
				var oldPwdIsCorrect = ValidateOldPassword(user.UserName, txtOldPwd.Text, out msg);

				if (oldPwdIsCorrect)
				{
					if (_UserProvider.ResetPassword(user))
					{
						ltrMsg.Text = "密码修改成功";
					}
					else
					{
						ltrMsg.Text = "密码修改失败";
					}
				}
				else
				{
					ltrMsg.Text = "旧密码验证失败 " + msg;
				}
			}
			else
			{
				Response.Redirect("~/Login.aspx");
			}
		}

		private bool ValidateOldPassword(string userName, string oldPwd, out string msg)
		{
			if (_UserProvider == null)
			{
				_UserProvider = new UserProvider();
			}

			var result = false;
			
			result = _UserProvider.ValidUser(userName, oldPwd, out msg);

			return result;
		}

		private void BindCurrentUser()
		{
			var user = SiteContext.Current.CurrentUser;

			if (user != null)
			{
				txtSecretAnswer1.Text = user.SecretAnswer1;
				txtSecretAnswer2.Text = user.SecretAnswer2;
				txtSecretQuestion1.Text = user.SecretQuestion1;
				txtSecretQuestion2.Text = user.SecretQuestion2;
			}
			else
			{
				Response.Redirect("~/Login.aspx");
			}
		}
	}
}